package com.handler;

import com.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * 全局异常处理器
 * @author muze
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLException.class)
    public Result sqlException(SQLException sqlException) {
        // 返回友好提示信息niz
        String message = sqlException.getMessage();
        return Result.fail(message);
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return handlerOtherException( e ) ;
    }

    @ExceptionHandler(RuntimeException.class)
    public Result runtimeException(RuntimeException e)
    {
        log.error(e.getMessage(), e);
        return Result.fail(e.getMessage());
    }

    public Result handlerOtherException(Exception e ){
        if(e.getCause().toString().startsWith( "java.sql.SQL" ) ){
            return Result.fail("数据操作失败！请联系管理员");
        }else{
            return Result.fail(e.getMessage());
        }
    }

    @ExceptionHandler(value=DataAccessException.class)
    public Result dataAccessErrorHandler(DataAccessException e){
        System.out.println("data access error handler");
        return Result.fail(e.getMessage());
    }

}